package com.glory.wxmemsicpda.activity

import android.annotation.SuppressLint
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.RadioGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.glory.wxmemsicpda.R
import com.glory.wxmemsicpda.adapter.CheckQueryListAdapter
import com.glory.wxmemsicpda.adapter.CheckQueryListAdapter.OnClickListener
import com.glory.wxmemsicpda.base.BaseDialogActivity
import com.glory.wxmemsicpda.bean.CheckSheetBean
import com.glory.wxmemsicpda.bean.EqpQueryBean
import com.glory.wxmemsicpda.bean.EquipMentBean
import com.glory.wxmemsicpda.bean.SheetInfoBean
import com.glory.wxmemsicpda.bean.net.BaseResponseBean
import com.glory.wxmemsicpda.utils.NetUtils
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.lzy.okgo.model.Response
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_SimpleDialogEntityCallBack
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ToastUtils
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils
import kotlinx.android.synthetic.main.activity_check_search.*
import kotlinx.android.synthetic.main.activity_check_search.llMain
import kotlinx.android.synthetic.main.activity_work_begin.*
import java.text.SimpleDateFormat
import java.util.*


/**
 * 点检履历
 */
open class CheckSearchActivity : BaseDialogActivity(), RadioGroup.OnCheckedChangeListener{
    private var mEqpType: String? = null
    private var mLocation: String? = null
    private var mSelectorStr = "ALL"
    private var sEqpId: String = ""

    private var mDataList: MutableList<SheetInfoBean?> = mutableListOf()
    private val mAdapter: CheckQueryListAdapter = CheckQueryListAdapter(mDataList)

    private var startTime = ""
    private var endTime = ""

    private var mDataNums: FreeUI_GeneralPop? = null


    override fun getLayoutResId(): Int {
        return R.layout.activity_check_search
    }

    override fun initView() {
        setTitle("点检履历")

        etEqpWork.requestFocus()

        freeUI_titleView.setRightListener("查询") {
            //region 测试
//            val mDataList2: MutableList<SheetInfoBean?> = mutableListOf()
//
//            //第一个条件防止未扫描就点击查询，第二个条件防止扫描完清空编辑框后点击查询
//            if (!TextUtils.isEmpty(sEqpId) && sEqpId == etEqpWork.text.toString()
//                    .replace(" ", "")
//            ) {
//                var sheetInfoBean = SheetInfoBean()
//                sheetInfoBean.grouP2 = "班次1"
//                sheetInfoBean.grouP1 = "时机1"
//                sheetInfoBean.objectrrn = "点检单号"
//                sheetInfoBean.equipmentid = etEqpWork.text.toString()
//                sheetInfoBean.reserveD1 = "位置1"
//                sheetInfoBean.equipmenttype = "型号1"
//
//                var currentTime = Date();
//                var formatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                var dateString = formatter.format(currentTime);
//                sheetInfoBean.created = dateString
//                sheetInfoBean.checkdate = dateString
//
//                sheetInfoBean.createdby = "张三"
//                sheetInfoBean.reserveD3 = "close"
//
//                mDataList2.add(sheetInfoBean)
//
//                var sheetInfoBean1 = SheetInfoBean()
//
//                sheetInfoBean1.grouP2 = "班次1"
//                sheetInfoBean1.grouP1 = "巡检"
//                sheetInfoBean1.objectrrn = "点检单号"
//                sheetInfoBean1.equipmentid = "设备号2"
//                sheetInfoBean1.reserveD1 = "位置2"
//                sheetInfoBean1.equipmenttype = "型号2"
//                sheetInfoBean1.created = dateString
//                sheetInfoBean1.checkdate = dateString
//                sheetInfoBean1.createdby = "张三"
//                sheetInfoBean1.reserveD3 = "Open"
//
//                mDataList2.add(sheetInfoBean1)
//
//                var sheetInfoBean2 = SheetInfoBean()
//
//                sheetInfoBean2.grouP2 = "班次2"
//                sheetInfoBean2.grouP1 = "交接班检"
//                sheetInfoBean2.objectrrn = "点检单号3"
//                sheetInfoBean2.equipmentid = etEqpWork.text.toString()
//                sheetInfoBean2.reserveD1 = "位置2"
//                sheetInfoBean2.equipmenttype = "型号2"
//                sheetInfoBean2.created = dateString
//                sheetInfoBean2.checkdate = dateString
//                sheetInfoBean2.createdby = "张三"
//                sheetInfoBean2.reserveD3 = "Open"
//
//                mDataList2.add(sheetInfoBean2)
//
//                mDataList.clear()
//                mAdapter.setNewData(getData(mDataList2))
//            } else {
//                showToast("请扫描设备编号", false)
//
//            }


            //endregion

            if (!TextUtils.isEmpty(sEqpId) && sEqpId == etEqpWork.text.toString()
                    .replace(" ", "")
            ) {
                //获取设备信息
                requestData()
            } else {

                showToast("请扫描设备编号", false)

            }
        }

        //初始化editText
        initEdit(etEqpWork, object : editTextListener {
            override fun onTextChangeListener(s: String) {

                sEqpId = s
                //region 测试
//                mEqpType = "型号1"
//                mLocation = "位置2"
                //endregion
                //获取当前设备型号和所在区域
//            searchEqpInfo(s)
            }
        })

        //region 时间选择
//        start_time.setOnClickListener(View.OnClickListener {  //获取实例，包含当前年月日
//            //获取实例，包含当前年月日
//            val calendar = Calendar.getInstance()
//            calendar.add(Calendar.DAY_OF_MONTH, -7);
//            val dialog = DatePickerDialog(
//                this, { _, year, month, dayOfMonth ->
//                    startTime = String.format("%d-%d-%d", year, month+1, dayOfMonth)
//                    start_time.text = startTime },
//                calendar[Calendar.YEAR],
//                calendar[Calendar.MARCH],
//                calendar[Calendar.DAY_OF_MONTH]
//            )
//            dialog.show() })
//
//        end_time.setOnClickListener(View.OnClickListener {  //获取实例，包含当前年月日
//            //获取实例，包含当前年月日
//            val calendar = Calendar.getInstance()
//            val dialog = DatePickerDialog(
//                this, { _, year, month, dayOfMonth ->
//                    endTime = String.format("%d-%d-%d", year, month+1, dayOfMonth)
//                    end_time.text = endTime },
//                calendar[Calendar.YEAR],
//                calendar[Calendar.MARCH],
//                calendar[Calendar.DAY_OF_MONTH]
//            )
//            dialog.show() });
        //endregion
        var testDataNumList: MutableList<String> =
            mutableListOf("50", "100", "150", "200", "250", "300", "400", "500", "700", "900")

        tvDataNum.setOnClickListener(View.OnClickListener {
            if (mDataNums != null) {
                if (mDataNums!!.isShowing) {
                    mDataNums!!.dismiss()
                }
            } else {
                mDataNums = FreeApi_PopUtils.getNormalPop(
                    applicationContext, tvDataNum.width, testDataNumList, ivDataNums
                ) { codeS: String?, i: Int ->
                    tvDataNum.text = codeS
                    mAdapter.setNewData(getData(listSort(mDataList), tvDataNum.text.toString()))
                }
            }
            FreeApi_PopUtils.setArrowShow(ivDataNums)
            mDataNums!!.showAsDropDown(tvDataNum, 0, 0)
        })

        rvCheckInfoList.layoutManager = LinearLayoutManager(this)
        rvCheckInfoList.adapter = mAdapter

        mAdapter.setOnCheckListener(object : OnClickListener {
            override fun onCheckListener(item: SheetInfoBean?) {
                if (item!!.reserveD3.equals("Open")) {
                    val bundle = Bundle()
                    bundle.putString("EQPID", item.equipmentid)
                    bundle.putString("OBJECTRRN", item.objectrrn)
                    if (item.grouP1.equals("巡检")) {

                        FreeApi_Utils.skipWithExtraIntent(
                            "header",
                            bundle,
                            this@CheckSearchActivity,
                            CheckInspectionActivity::class.java
                        )
                    } else {
                        FreeApi_Utils.skipWithExtraIntent(
                            "header",
                            bundle,
                            this@CheckSearchActivity,
                            CheckTableActivity::class.java
                        )
                    }
                } else {
                    FreeApi_ToastUtils.showFreeToast("当前状态不允许", this@CheckSearchActivity, false, 0)
                }
            }
        })

        rgType.setOnCheckedChangeListener(this)

    }

    override fun initData() {
        //region 时间选择
//        var instance = Calendar.getInstance()
//        endTime = String.format(
//            "%d-%d-%d",
//            instance[Calendar.YEAR],
//            instance[Calendar.MONTH],
//            instance[Calendar.DAY_OF_MONTH]
//        )
//        instance.add(Calendar.DAY_OF_MONTH, -7);
//        startTime = String.format(
//            "%d-%d-%d",
//            instance[Calendar.YEAR],
//            instance[Calendar.MONTH],
//            instance[Calendar.DAY_OF_MONTH]
//        )
        //endregion

        tvDataNum.text = "200"
    }

    override fun getBaseEntity(): FreeUI_AddViewEntity {
        return FreeUI_AddViewEntity("header", llMain)
    }

    //region 接口调用

    //获取当前设备型号和所在区域
    private fun searchEqpInfo(eqpID: String?) {
        val map = JsonObject()
        map.addProperty("ACTIONTYPE", "LOAD")
        val equipMentEntity = EquipMentBean()
        equipMentEntity.equipmentid = eqpID
        map.add("EQUIPMENT", JsonParser().parse(Gson().toJson(equipMentEntity)).asJsonObject)
        NetUtils.requestMesPosNet(this,
            "EQPQUERY", "CPC.EQPQUERY",
            map,
            object : FreeUI_SimpleDialogEntityCallBack<BaseResponseBean<EqpQueryBean?>?>(
                this
            ) {
                override fun onSuccess(response: Response<BaseResponseBean<EqpQueryBean?>?>) {
                    super.onSuccess(response)
                    if (response.body()!!.isSuccess(true, supportFragmentManager)) {
                        mEqpType = response.body()!!.response.body?.equipment?.eqptype
                        mLocation = response.body()!!.response.body?.equipment?.location
                    }
                }

                override fun onError(response: Response<BaseResponseBean<EqpQueryBean?>?>) {
                    super.onError(response)
                    loadError(response.exception, "EQPQUERY")
                }
            })
    }

    //获取设备信息
    private fun requestData() {
        val map = JsonObject()
        map.addProperty("EQUIPMENTID", etEqpWork.text.toString())
//        map.addProperty("ACTIONTYPE", "QUERYALL")
        map.addProperty("ACTIONTYPE", "QUERY")

        NetUtils.requestMesPosNet(this,
            "CHECKSHEETQUERY", "MEMSIC.CHECKSHEETQUERY",
            map,
            object : FreeUI_SimpleDialogEntityCallBack<BaseResponseBean<CheckSheetBean?>?>(this) {
                override fun onSuccess(response: Response<BaseResponseBean<CheckSheetBean?>?>) {
                    super.onSuccess(response)
                    if (response.body()!!.isSuccess(true, supportFragmentManager)) {
                        val sheetlist =
                            response.body()!!.response.body?.sheetlist as MutableList<SheetInfoBean?>
                        mDataList = response.body()!!.response.body?.sheetlist as MutableList<SheetInfoBean?>
                        if (sheetlist.isEmpty()) {
                            FreeApi_DialogUtils.getConfirmDialog(this@CheckSearchActivity,
                                "确定",
                                "暂无数据",
                                {})
                                .show(supportFragmentManager, "CONFIRM_DIALOG")
                        }


                        mAdapter.setNewData(getData(listSort(sheetlist), tvDataNum.text.toString()))

                    }
                }

                override fun onError(response: Response<BaseResponseBean<CheckSheetBean?>?>?) {
                    super.onError(response)
                    loadError(response?.exception, "CHECKSHEETQUERY")

                }
            })
    }

    //endregion

    //获取指定类型数据
    private fun getData(sheetList: MutableList<SheetInfoBean?>): MutableList<SheetInfoBean?> {
        var list: MutableList<SheetInfoBean?> = ArrayList<SheetInfoBean?>()
        when (mSelectorStr) {
            "ALL" -> list.addAll(sheetList)
            "SINGLE" -> for (entity in sheetList) {
                if (entity?.equipmentid.equals(etEqpWork.text.toString())) {
                    list.add(entity)
                }
            }
            "LOCATION" -> for (entity in sheetList) {
                if (entity?.reserveD1.equals(mLocation)) {
                    list.add(entity)
                }
            }
            "EQPTYPE" -> for (entity in sheetList) {
                if (entity?.equipmenttype.equals(mEqpType)) {
                    list.add(entity)
                }
            }
        }
        return list
    }

    //获取指定数量数据
    private fun getData(sheetList: MutableList<SheetInfoBean?>, dataNum: String): MutableList<SheetInfoBean?> {
        var list: MutableList<SheetInfoBean?> = ArrayList<SheetInfoBean?>()
        var i = 1;
        var nDataNum = if (dataNum == "") 0 else dataNum.toInt()

        for (entity in sheetList){
            if (i++ <= nDataNum){
                list.add(entity)
            }
        }
        return list
    }

    @SuppressLint("SimpleDateFormat")
    private fun listSort(list: MutableList<SheetInfoBean?>) :MutableList<SheetInfoBean?>{
        list.sortWith(Comparator { sheetInfoEntity, t1 ->
            val format = SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
            try {
                val dt1 = format.parse(sheetInfoEntity?.checkdate)
                val dt2 = format.parse(t1?.checkdate)
                when {
                    dt1.time < dt2.time -> {
                        return@Comparator 1
                    }
                    dt1.time > dt2.time -> {
                        return@Comparator -1
                    }
                    else -> {
                        return@Comparator 0
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            0
        })
        return list
    }

    override fun onCheckedChanged(group: RadioGroup?, checkedId: Int) {
        when (checkedId) {
            R.id.rbSingleEqp -> {
                mSelectorStr = "SINGLE"
            }
            R.id.rbEqp -> {
                mSelectorStr = "EQPTYPE"
            }
            R.id.rbLocation -> {
                mSelectorStr = "LOCATION"
            }
            R.id.rbAll -> {
                mSelectorStr = "ALL"
            }
        }
    }

    override fun onRestart() {
        super.onRestart()
        requestData()
    }
}